package comptest;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @version 1.8
 * @Author Djx_hmbb
 * @Date 2023/8/5 17:44
 * @注释:JDBCSelect
 * select-->executeQuery
 */
public class JDBCSelect {
    public static void main(String[] args) throws SQLException {
        //1.创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/stu?serverTimezone=GMT%2B8&userSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.和数据库服务器连接
        Connection connection = (Connection) dataSource.getConnection();
        //3.构造SQL语句；
        String sql = "select * from books";
        PreparedStatement pms = connection.prepareStatement(sql);
        //4.执行SQL语句
//        int ret = pms.executeUpdate();
        ResultSet resultSet = pms.executeQuery(sql);//返回表
        //遍历结果集
        while(resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");//括号里的可以填：列名（建议）、列号
//            String author = resultSet.getString("author");
//            double price = resultSet.getDouble("price");
            String kinds = resultSet.getString("kinds");
//            String year = resultSet.getString("year");

//            System.out.println(" id="+id+" name="+name+" author="+author+" price"+price+" kinds="+kinds+" year"+year);
            System.out.println(" id="+id+" name="+name+" kinds="+kinds);
        }

        //6.释放必要的资源
        resultSet.close();
        pms.close();
        connection.close();
    }
}
